package ua.com.minus1.lookbattle;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import ua.com.minus1.lookbattle.models.BonusConvertResult;
import ua.com.minus1.lookbattle.models.CommonResult;
import ua.com.minus1.lookbattle.models.Look;
import ua.com.minus1.lookbattle.net.HttpManager;
import ua.com.minus1.lookbattle.net.ImageManager;
import ua.com.minus1.lookbattle.net.URLManager;
import ua.com.minus1.lookbattle.utils.AppPreferences;
import ua.com.minus1.lookbattle.utils.BundleCreator;

/**
 * Created with IntelliJ IDEA.
 * User: Flash
 * Date: 19.07.12
 * Time: 13:12
 * To change this template use File | Settings | File Templates.
 */
public class LookActivity extends Activity {
    private int lookId;
    private TextView globalPlace;
    private TextView winnings;
    private TextView localPlace;
    private TextView battles;
    private TextView creationDate;
    private HttpManager httpManager;
    private TextView bonuses;
    private ImageManager imageManager;
    private ImageView image;
    private View progress;
    private int catId;
    private AppPreferences preferences;
    private String uuid;
    private TextView country;
    private Look look;

    private static final int DIALOG_CONVERT = 0;
    private static final int DIALOG_CONFIRM = 1;
    private Button convertBtn;
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_look_details);

        catId = BundleCreator.readCategory(getIntent().getExtras());
        preferences = new AppPreferences(this);
        uuid = preferences.getUUID();

        Bundle bundle = getIntent().getExtras();
        if(bundle != null) {
            lookId = BundleCreator.readLookId(bundle);
            position = BundleCreator.readPosition(bundle);
        }


        setupView();

        imageManager = new ImageManager(this);

        httpManager = new HttpManager(this);
        httpManager.loadClass(URLManager.getLookInfoURL(uuid, catId, lookId), Look.class, new HttpManager.HttpResultHandler<Look>() {
            public void onResultLoadComplete(Look result) {
                Log.i(LookActivity.class.getName(), "Look: " + lookId + " request result: " + result.toString());
                look = result;
                updateLook();
            }
        });
    }

    private void setupView() {
        creationDate = (TextView) findViewById(R.id.lookInfoCreationDate);
        country = (TextView) findViewById(R.id.lookInfoCountry);
        globalPlace = (TextView) findViewById(R.id.loookRatesGlobalPlace);
        localPlace = (TextView) findViewById(R.id.lookRatesLocalPace);
        winnings = (TextView) findViewById(R.id.lookRatesWinnings);
        battles = (TextView) findViewById(R.id.lookRatesBattles);
        bonuses = (TextView) findViewById(R.id.lookBonuses);
        image = (ImageView) findViewById(R.id.lookInfoImage);
        progress = findViewById(R.id.lookInfoProgress);
        convertBtn = (Button) findViewById(R.id.lookItemConvertBtn);
        convertBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                showDialog(DIALOG_CONVERT);
            }
        });
    }

    private void updateLook() {
        bonuses.setText(String.valueOf(look.bonuses));
        globalPlace.setText(String.valueOf(look.globalPlace));
        localPlace.setText(String.valueOf(look.localPlace));
        battles.setText(String.valueOf(look.battles));
        winnings.setText(String.valueOf(look.winnings));
        creationDate.setText(look.date);
        if(look.countryId != -1)
            country.setText(CountriesFactory.getCountry(this, look.countryId).name);
        //progress.setVisibility(View.VISIBLE);
        //image.setImageBitmap(null);
        imageManager.loadBitmap(look.image, image, new ImageManager.BitmapLoadListener() {
            public void onLoadComplete(Bitmap bitmap) {
                progress.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_CONVERT:
                return new ConvertDialog(this).setConvertListener(new ConvertDialog.OnConvertListener() {
                    public void onClick(DialogInterface dialogInterface, int position, int lookId, int bonuses) {
                        if (bonuses != 0) {
                            final int itemPos = position;
                            String url = bonuses > 0 ? URLManager.getBonusUpUrl(uuid, catId, lookId, bonuses) : URLManager.getBonusRefundUrl(uuid, catId, lookId, Math.abs(bonuses));
                            Log.i(LookActivity.class.getName(), "request for bonus update catId: " + catId + " lookId: " + lookId + " bonuses: "+bonuses + " url: " + url);
                            httpManager.loadClass(url, BonusConvertResult.class, new HttpManager.HttpResultHandler<BonusConvertResult>() {
                                public void onResultLoadComplete(BonusConvertResult result) {
                                    Log.i(LookActivity.class.getName(), "bonus convert result: " + result.toString());
                                    preferences.setClicks(result.clicks);
                                    //clickText.setText(String.valueOf(result.clicks));
                                    onBonusConvert(result.bonuses, itemPos, result.clicks);
                                }
                            });
                        }
                        dialogInterface.cancel();
                    }
                });
            case DIALOG_CONFIRM:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Delete look")
                        .setMessage("Are you sure you want to delete this look?")
                        .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogInterface, int i) {
                                deleteLook();
                                dialogInterface.dismiss();
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        });
                return builder.create();
            default:
                return null;
        }
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
        super.onPrepareDialog(id, dialog, args);
        switch (id) {
            case DIALOG_CONVERT:
                ((ConvertDialog) dialog).setParams(ConvertDialog.getBundle(position, lookId, look.bonuses, preferences.getClicks()));
                break;
        }
    }

    private void onBonusConvert(int b, int itemPos, int clicks) {
        bonuses.setText(String.valueOf(b));

        BundleCreator creator = new BundleCreator();
        creator.writeBonuses(b)
                .writePosition(itemPos)
                .writeClicks(clicks);

        Intent intent = new Intent();
        intent.putExtras(creator.create());
        setResult(RESULT_OK, intent);
    }

    public void onDelete(View view) {
         showDialog(DIALOG_CONFIRM);
    }

    private void deleteLook(){
        httpManager.loadClass(URLManager.getDeleteLookURL(uuid, lookId, catId), CommonResult.class, new HttpManager.HttpResultHandler<CommonResult>() {
            public void onResultLoadComplete(CommonResult result) {
                Log.i(LookActivity.class.getName(), "delete look result: " + result.toString());
                Intent intent = new Intent();
                intent.putExtra("delete", true);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }
}
